<template>
  <view class="page-song">
    <scroll-view class="page-song__list" scroll-y :scroll-top="scrollTop">
      <view 
        class="list__item" 
        v-for="(lyric, index) in lyricList" 
        :key="index"
        :class="{ 'active': index === currentLyricIndex }">
        {{ lyric.text }}
      </view>
    </scroll-view>
  </view>
</template>

<script>
  const app = getApp()
  
  export default {
    data() {
      return {
        lyricList: [],
        
        currentLyricIndex: 0, // 当前的歌词下标
      }
    },
     
    computed: {
      scrollTop () {
        let oneHeight = 72 * app.rpxBili
        return (this.currentLyricIndex - 2) * oneHeight
      }
    },
    
    methods: {
      /**
       * 获取音乐播放地址
       * @param {Object} id
       */
      getUrl(id) {
        return new Promise((resolve, reject) => {
          uni.request({
            url: 'http://10.36.147.90:3000/song/url',
            data: {
              id: id
            },
            success: ({
              data
            }) => {
              if (data.code === 200) {
                const url = data.data[0].url
                resolve(url)
              } else {
                reject(new Error('获取播放地址失败'))
              }
            }
          })
        })
      },

      /**
       * 获取歌曲的歌词
       * @param {Object} id
       */
      getLyric(id) {
        return new Promise((resolve, reject) => {
          uni.request({
            url: 'http://10.36.147.90:3000/lyric',
            data: {
              id: id
            },
            success: ({
              data
            }) => {
              if (data.code === 200) {
                resolve(data.lrc.lyric)
              } else {
                reject(new Error('获取歌曲歌词失败'))
              }
            }
          })
        })
      },

      /**
       * 解析歌词并渲染页面
       * @param {Object} lyric
       */
      compileLyric(lyric) {
        // 0. 定义一个 result 
        let result = []
        // 1. 先用 \n 做为分隔符来讲 歌词字符串 分割成 歌词数组
        let tmpArr = lyric.split('\n')
        // 2. 循环歌词数组
        for (let i = 0; i < tmpArr.length; i++) {
          let item = tmpArr[i]

          if (!item) continue

          let timeReg = /\[(.*)\]/ // 时间正则
          let text = item.replace(timeReg, '') // 取出歌词的纯文本

          let timeStr = item.match(timeReg)[1] // 取出形如 01:02.22 这个时间格式

          let min = parseInt(timeStr.split(':')[0])
          let sec = parseInt(timeStr.split(':')[1])
          let time = min * 60 + sec

          result.push({
            time,
            text
          })
        }
        
        // 3. 将result渲染到页面上
        this.lyricList = result
      },

      play(url) {
        // 获取app实例
        app.audioCtx.stop()
        app.audioCtx.src = url
        app.audioCtx.play();
        
        // 监听当前的播放进行
        app.audioCtx.onTimeUpdate(() => {
          // 获取当前播放进度
          let currentTime = app.audioCtx.currentTime
          
          for (let i = this.currentLyricIndex; i < this.lyricList.length; i++) {
            let item = this.lyricList[i]
            if (currentTime >= item.time) {
              this.currentLyricIndex = i
            }
          }
        })
        
      }
    },

    async onLoad({
      id
    }) {
      // 1. 获取音乐的播放地址
      const url = await this.getUrl(id)
      // 2. 获取音乐的歌词
      const lyric = await this.getLyric(id)
      // 3. 解析歌词为数组对象的形式
      this.compileLyric(lyric)
      // 3. 播放
      this.play(url)
    }
  }
</script>

<style lang="scss">
  page {
    height: 100%;
  }

  .page-song {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;

    &__list {
      text-align: center;
      width: 80vw;
      height: 360rpx;
    }

    .list__item {
      height: 72rpx;
      line-height: 72rpx;
      color: #333333;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;

      &.active {
        color: #ff0000;
      }
    }
  }
</style>
